package com.hyz.service.impl;

import com.hyz.pojo.LoginUser;
import com.hyz.pojo.ResponseResult;
import com.hyz.pojo.User;
import com.hyz.service.LoginService;
import com.hyz.util.JwtUtil;
import com.hyz.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author HGD
 * @date 2022/9/15 12:54
 * 获取用户账号和密码进行验证
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult<Map<String, String>> login(User user) {
        // 2. 因为 Authentication 是一个接口 Authentication authentication = new Authentication();
        //    所以我们可以创建一个 Authentication 的实现类 UsernamePasswordAuthenticationToken 传入账号和密码
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());

        //1.通过 AuthenticationManager 接口对象的实现类 ProviderManager 的 authenticate(Authentication authentication) 方法
        //  将用户的账号和密码传入 authenticate 方法中，就可以用来判断账号和密码是否正确
        // 如果正确则将所有的用户数据用 Authentication 对象来接受并返回
        // 如果错误则返回一个空的 Authentication 对象
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);

        // 3. 通过 authenticate 是否为空来判断用户输入的账号和密码是否正确
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户的密码错误");
        }

        // 4. 将获取的数据生成为
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = String.valueOf(loginUser.getUser().getId());
        String jwt = JwtUtil.createJWT(userId);
        Map<String, String> map = new HashMap<>(1);
        map.put("token", jwt);
        redisCache.setCacheObject("login:" + userId, loginUser);
        return new ResponseResult<>(200, "登录成功", map);
    }

    @Override
    public ResponseResult<String> logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = String.valueOf(loginUser.getUser().getId());
        redisCache.deleteObject("login:" + userId);
        return new ResponseResult<>(200, "退出成功", null);
    }
}
